// $Id$
// Licensed under Apache License Version 2.0
// See: http://www.apache.org/licenses/LICENSE-2.0.html
package de.servicezombie.cxf;

import java.io.StringReader;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;

import org.apache.commons.lang.ArrayUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class JaxbUtils {

	private static final Logger log = LoggerFactory.getLogger(JaxbUtils.class);

	public static Unmarshaller buildUnmarshaller(Class<?>... types) throws JAXBException {
		JAXBContext jaxbContext = JAXBContext.newInstance(types);
		Unmarshaller m = jaxbContext.createUnmarshaller();
		return m;
	}

	public static Marshaller buildMarshallerForTest(Class<?>... types) throws JAXBException {
		JAXBContext jaxbContext = JAXBContext.newInstance(types);
		Marshaller m = jaxbContext.createMarshaller();
		m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
		return m;
	}

	@SuppressWarnings("unchecked")
	public static <T> T unmarshall(String input, Class<?>... types) throws IllegalArgumentException {
		if (log.isDebugEnabled()) {
			log.debug("unmarshall: >> '" + input + "', " + ArrayUtils.toString(types));
		}

		T result;

		try {
			Unmarshaller um = buildUnmarshaller(types);
			result = (T) um.unmarshal(new StringReader(input));
		}
		catch (JAXBException e) {
			throw new IllegalArgumentException("unable to marshal input data: " + e.getMessage(), e);
		}

		if (log.isDebugEnabled()) {
			log.debug("unmarshall: << " + result);
		}
		return result;
	}

}
